package cn.com.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class MessageUtil {

	/**
	 * 将微信服务器发过来的信息，封装成Map，
	 * 
	 * @param req
	 * @return
	 * @throws IOException
	 */
	public static Map<String, String> parseXmlMessage(HttpServletRequest req)
			throws IOException {
		BufferedReader reader = req.getReader();
		Map<String, String> resultMap = new HashMap<String, String>();

		SAXReader saxReader = new SAXReader();
		Document doc;
		try {
			doc = saxReader.read(reader);
			@SuppressWarnings("unchecked")
			List<Element> elements = doc.getRootElement().elements();

			for (Element e : elements) {
				String elementName = e.getName();
				String elementValue = e.getText();
				resultMap.put(elementName, elementValue);
				if (elementName.equals("Content")) {
					String root = req.getSession().getServletContext()
							.getRealPath("/");
					File f = new File(root, "recievedMessages.txt");
					FileWriter writer = new FileWriter(f, true);
					writer.write(elementValue);
					writer.flush();
					writer.close();
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * 将微信服务器发过来的信息，封装成Map，
	 * 
	 * @param req
	 * @return
	 * @throws IOException
	 */
	public static Map<String, String> parseXmlMessage(Reader reader)
			throws IOException {
		Map<String, String> resultMap = new HashMap<String, String>();

		SAXReader saxReader = new SAXReader();
		Document doc;
		try {
			doc = saxReader.read(reader);
			@SuppressWarnings("unchecked")
			List<Element> elements = doc.getRootElement().elements();

			for (Element e : elements) {
				String elementName = e.getName();
				String elementValue = e.getText();
				resultMap.put(elementName, elementValue);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return resultMap;
	}

}
